package org.wisigoth.chat.swing.chatscreen;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JTabbedPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;

import org.wisigoth.chat.client.ChatSession;
import org.wisigoth.chat.client.Contact;
import org.wisigoth.chat.client.Message;
import org.wisigoth.chat.client.WisigothUser;
import org.wisigoth.chat.client.msg.ChatMessage;
import org.wisigoth.chat.swing.WisigothController;
import org.wisigoth.chat.swing.chatscreen.ButtonTabComponent.TabButton;

public class ChatController implements KeyListener, ActionListener,
		WindowListener {

	private final List<ChatPanel> chatPanelList;
	private final WisigothController parent;
	private final ChatFrame chatFrame;

	public ChatController(WisigothController wisigothController) {
		this.parent = wisigothController;
		this.chatPanelList = new ArrayList<ChatPanel>();
		this.chatFrame = new ChatFrame(this);
		this.chatFrame.addWindowListener(this);
	}

	@Override
	public void keyPressed(KeyEvent e) {

		if (e.getKeyCode() == KeyEvent.VK_ENTER) {
			javax.swing.JTextPane promptArea = (JTextPane) e.getSource();
			String bodyMessage = (promptArea.getText() == null) ? ""
					: promptArea.getText().trim();
			if (!"".equals(bodyMessage)) {
				ChatPanel chatPanel = (ChatPanel) SwingUtilities
						.getAncestorOfClass(ChatPanel.class, promptArea);
				WisigothUser from = this.parent.getSession().whoAmI();
				WisigothUser to = chatPanel.getSession().getContact().getUser();
				ChatMessage message = new ChatMessage(from, to, bodyMessage);
				chatPanel.getSession().sendMessage(message);
				this.refreshChat(chatPanel, message);

			}
		}
	}

	/**
	 * Refresh the given {@link ChatPanel} with the given {@link Message}
	 * 
	 * @param chatPanel
	 * @param message
	 */
	public void refreshChat(ChatPanel chatPanel, Message message) {

		JTextPane chatArea = chatPanel.getChat();
		String chatDisplay = chatArea.getText()
				+ message.getFrom().getNickName() + " : "
				+ ((ChatMessage) message).getText()
				+ System.getProperty("line.separator");
		chatArea.setText(chatDisplay);

	}

	@Override
	public void keyReleased(KeyEvent e) {
		if (e.getKeyChar() == KeyEvent.VK_ENTER) {
			javax.swing.JTextPane promptArea = (JTextPane) e.getSource();
			ChatPanel chatPanel = (ChatPanel) SwingUtilities
					.getAncestorOfClass(ChatPanel.class, promptArea);
			chatPanel.getPrompt().setText("");
		}

	}

	@Override
	public void keyTyped(KeyEvent e) {
		if (e.getKeyChar() == KeyEvent.VK_ENTER) {
			e.consume();
		}
	}

	public ChatPanel getChatPanel(ChatSession chatSession) {
		for (ChatPanel panel : this.chatPanelList) {
			if (panel.getSession() == chatSession) {
				return panel;
			}
		}
		return null;
	}

	public void openChat(ChatSession chatSession) {
		ChatPanel chatPanel = this.getChatPanel(chatSession);
		if (chatPanel == null) {
			chatPanel = new ChatPanel(this.chatFrame, chatSession);
			chatPanel.getPrompt().addKeyListener(this);
			this.addChatPanel(chatPanel);

		}
		// chatPanel.setVisible(true);
	}

	private void addChatPanel(ChatPanel chatPanel) {
		if (this.chatPanelList.size() == 0) {

			this.chatFrame.add(chatPanel);
			this.chatFrame.pack();
			this.chatFrame.setVisible(true);

		} else if (this.chatPanelList.size() == 1) {
			ChatPanel firstChatPanel = this.chatPanelList.get(0);
			this.chatFrame.remove(firstChatPanel);

			/**
			 * Create the tabbed Pane
			 */

			String title = firstChatPanel.getSession().getContact().getUser()
					.getNickName();
			this.chatFrame.getTabbedPane().add(title, firstChatPanel);
			this.initTabComponent(0);
			this.chatFrame.getTabbedPane().setSelectedIndex(0);
			
			title = chatPanel.getSession().getContact().getUser()
			.getNickName();
			this.chatFrame.getTabbedPane().add(title, chatPanel);
			this.initTabComponent(1);
			this.chatFrame.getTabbedPane().setSelectedIndex(1);

			
			this.chatFrame.getTabbedPane().setTabLayoutPolicy(
					JTabbedPane.SCROLL_TAB_LAYOUT);
			this.chatFrame.add(this.chatFrame.getTabbedPane());
			this.chatFrame.getContentPane().validate();
			this.chatFrame.pack();
			this.chatFrame.getTabbedPane().setVisible(true);

		} else {
			String title = chatPanel.getSession().getContact().getUser()
					.getNickName();
			this.chatFrame.getTabbedPane().add(title, chatPanel);
			this.initTabComponent(this.chatPanelList.size());
			this.chatFrame.getTabbedPane().setSelectedIndex(
					this.chatPanelList.size());

		}
		this.chatPanelList.add(chatPanel);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		ButtonTabComponent buttonTab = ((TabButton) e.getSource())
				.getTabComponent();
		int i = this.chatFrame.getTabbedPane().indexOfTabComponent(buttonTab);
		if(i == -1){
			return;
		}
		this.chatFrame.getTabbedPane().remove(i);
		this.closeChat(i);
		this.chatPanelList.remove(i);

		if (this.chatFrame.getTabbedPane().getTabCount() == 1) {
			this.chatFrame.getTabbedPane().setVisible(false);
			this.chatFrame.add(this.chatPanelList.get(0));
			this.chatFrame.pack();
			this.chatFrame.setVisible(true);
		}
		
	}

	public void initTabComponent(int i) {
		ButtonTabComponent buttonTab = new ButtonTabComponent(this.chatFrame
				.getTabbedPane());
		this.chatFrame.getTabbedPane().setTabComponentAt(i, buttonTab);
		buttonTab.getButton().addActionListener(this);

	}

	public void closeChat(int i) {

		ChatPanel chatPanel = this.chatPanelList.get(i);
		chatPanel.getSession().removeMessageConsumer(chatPanel);
		this.parent.getSession().closeChat(chatPanel.getSession());

	}

	@Override
	public void windowActivated(WindowEvent e) {

	}

	@Override
	public void windowClosed(WindowEvent e) {

	}

	@Override
	public void windowClosing(WindowEvent e) {
		int numChat = this.chatPanelList.size();
		if (numChat > 1) {
			for (int i = 0; i < numChat; i++) {
				this.closeChat(i);
			}
			this.chatFrame.getTabbedPane().removeAll();
			this.chatFrame.getTabbedPane().setVisible(false);
		} else {
			this.chatFrame.remove(this.chatPanelList.get(0));
			this.closeChat(0);
		}
		this.chatPanelList.clear();
		this.chatFrame.setVisible(false);

	}

	public boolean isChatted(Contact contact) {
		for (ChatPanel panel : this.chatPanelList) {
			if (panel.getSession().getContact() == contact) {
				return true;
			}
		}
		return false;
	}

	@Override
	public void windowDeactivated(WindowEvent e) {

	}

	@Override
	public void windowDeiconified(WindowEvent e) {
	}

	@Override
	public void windowIconified(WindowEvent e) {
	}

	@Override
	public void windowOpened(WindowEvent e) {
	}

	public void setFocus(Contact contact) {

		int numChat = this.chatPanelList.size();
		if (numChat > 1) {
			for (int i = 0; i < numChat; i++) {
				if (this.chatPanelList.get(i).getSession().getContact().equals(
						contact))
					this.chatFrame.getTabbedPane().setSelectedIndex(i);
			}

		} else {
			this.chatFrame.setVisible(true);
		}

	}

}
